<?php


namespace App\Helpers;


use App\Exceptions\ApiException;
use App\Library\TencentCloud\SensitiveWordsApi;
use App\Traits\Library\GetLibraryTrait;
use Exception;

/**
 * 敏感词检测助手类
 *
 * Class SensitiveWordsHelper
 *
 * @package App\Helpers
 * @author  kingsg
 */
class SensitiveWordsHelper extends Helper
{
	const DEFAULT_KEYWORD = "未知";

	/**
	 * 检测敏感词
	 *
	 * @param string $content
	 * @throws Exception
	 */
	public static function checkSensitiveWords(string $content)
	{
		// 敏感词校验
		$resp = GetLibraryTrait::geSensitiveWordsApi()->textModeration($content);
		LogHelper::info('checkSensitiveWords', $resp);

		// 判断：后续操作建议
		$suggestion = $resp->getSuggestion();
		if ($suggestion == SensitiveWordsApi::SUGGESTION_PASS) {
			return;
		}

		// 判断：返回检测结果
		$label = $resp->getLabel();
		if (in_array($label, [
			SensitiveWordsApi::LABEL_NORMAL,
			SensitiveWordsApi::LABEL_AD,
		])) {
			return;
		}

		// 判断敏感词： 取第一个敏感词
		$keywords = $resp->getKeywords();
		if (count($keywords) == 0) {
			$keyword = self::DEFAULT_KEYWORD;
		} else {
			$keyword = $keywords[0];
		}

		throw  new ApiException('内容含敏感词:' . $keyword, ApiException::CODE_1101);
	}
}